﻿using System;
using System.Web;
using ASPItalia.ModelVirtualCasting.EntityFramework.Wrappers;

namespace ASPItalia.ModelVirtualCasting.EntityFramework
{
	public class WebContextModule : IHttpModule
	{
		public void Dispose()
		{
		}

		public void Init(HttpApplication context)
		{
			context.BeginRequest += new EventHandler(context_BeginRequest);
			context.EndRequest += new EventHandler(context_EndRequest);
		}

		void context_EndRequest(object sender, EventArgs e)
		{
			var ctx = ((ContextWrapper)HttpContext.Current.Items["EFObjectContext"]);

            if (ctx != null)
            {
                ctx.Dispose();
            }
		}

		void context_BeginRequest(object sender, EventArgs e)
		{
			HttpContext.Current.Items["EFObjectContext"] = new ContextWrapper(new ModelVirtualCastingEntities(Configuration.ConnectionString));
		}
	}
}
